package com.yogee.topseller.activity;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.common.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.SharedPreferencesUtils;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.base.HttpActivity;
import com.yogee.topseller.adapter.ProductDetailItemAdapter;
import com.yogee.topseller.adapter.ZixunAdapter;
import com.yogee.topseller.bean.CollectBean;
import com.yogee.topseller.bean.MySelfInfo;
import com.yogee.topseller.bean.PKBean;
import com.yogee.topseller.bean.ProductInfoBean;
import com.yogee.topseller.bean.ResultBean;
import com.yogee.topseller.bean.ResultBean1;
import com.yogee.topseller.bean.ShareProductBean;
import com.yogee.topseller.bean.ZixunBean;
import com.yogee.topseller.fragment.FreeFragment;
import com.yogee.topseller.fragment.ShouchongFragment;
import com.yogee.topseller.fragment.ZhuanyeFragment;
import com.yogee.topseller.fragment.productdetail.AccountFragment;
import com.yogee.topseller.fragment.productdetail.BaseInfoFragment;
import com.yogee.topseller.fragment.productdetail.ProductListFragment;
import com.yogee.topseller.fragment.productdetail.ProductPictFragment;
import com.yogee.topseller.fragment.zhoubian.DingyueFragment;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.layout.GoodBadDialogFragment;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.LogUtils;
import com.yogee.topseller.utils.TabLayoutUtil;
import com.yogee.topseller.view.BasicDialog1;
import com.yogee.topseller.view.FlowLayoutOther;
import com.yogee.topseller.view.PullUpToLoadMore;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/12/5.
 */

public class ProductDetailsActivity extends HttpActivity {

    @BindView(R.id.details_compare_num_tv)
    TextView details_compare_num_tv;  // 对比显示的条数
    @BindView(R.id.details_pro_name_tv)
    TextView details_pro_name_tv;  // 商品名称
    @BindView(R.id.tv_detail)
    TextView tv_detail;  // 商品名称下边的文字
    @BindView(R.id.tv_detail_qt)
    TextView tv_detail_qt;  // 起投
    @BindView(R.id.tv_detail_sy)
    TextView tv_detail_sy;  // 收益
    @BindView(R.id.tv_detail_qx)
    TextView tv_detail_qx;  // 期限
    @BindView(R.id.tv_detail_now_info)
    TextView tv_detail_now_info;  // 实时信息

    @BindView(R.id.details_rate_money1_tv)
    TextView details_rate_money1_tv;
    @BindView(R.id.details_rate_profit1_tv)
    TextView details_rate_profit1_tv;
    @BindView(R.id.details_rate_rebate1_tv)
    TextView details_rate_rebate1_tv;
    @BindView(R.id.details_rate_money2_tv)
    TextView details_rate_money2_tv;
    @BindView(R.id.details_rate_profit2_tv)
    TextView details_rate_profit2_tv;
    @BindView(R.id.details_rate_rebate2_tv)
    TextView details_rate_rebate2_tv;
    @BindView(R.id.details_rate_money3_tv)
    TextView details_rate_money3_tv;
    @BindView(R.id.details_rate_profit3_tv)
    TextView details_rate_profit3_tv;
    @BindView(R.id.details_rate_rebate3_tv)
    TextView details_rate_rebate3_tv;

    @BindView(R.id.details_lable_flowlayout)
    FlowLayoutOther details_lable_flowlayout;   // 亮点标签

    @BindView(R.id.details_state_pb)
    ProgressBar details_state_pb;   // 募集进度
    @BindView(R.id.details_state_pro_tv)
    TextView details_state_pro_tv;

    @BindView(R.id.details_state_type_tv)
    TextView details_state_type_tv;  // 产品状态
    @BindView(R.id.details_fxfs_tv)
    TextView details_fxfs_tv;  // 付息方式
    @BindView(R.id.details_rate_1_ll)
    LinearLayout details_rate_1_ll;
    @BindView(R.id.details_rate_2_ll)
    LinearLayout details_rate_2_ll;
    @BindView(R.id.details_rate_3_ll)
    LinearLayout details_rate_3_ll;
    @BindView(R.id.details_rate_ll)
    LinearLayout details_rate_ll;
    @BindView(R.id.details_plus_tv)
    TextView details_plus_tv;
    @BindView(R.id.details_collection_tv)
    TextView details_collection_tv;
    @BindView(R.id.details_pro_tv)
    TextView details_pro_tv;
    @BindView(R.id.img_tu)
    ImageView img_tu;
    @BindView(R.id.img_yu)
    ImageView img_yu;
    @BindView(R.id.etails_plus_rl)
    RelativeLayout etails_plus_rl;
    @BindView(R.id.ptlm)
    PullUpToLoadMore ptlm;
    @BindView(R.id.ll_sh)
    LinearLayout ll_sh;
    @BindView(R.id.rv_product_detail)
    RecyclerView rv_product_detail;
    @BindView(R.id.rl_product_details_new)
    RelativeLayout rl_product_details_new;
    @BindView(R.id.ll_goto_detail)
    LinearLayout ll_goto_detail;
    @BindView(R.id.tv_qy_num)
    TextView tv_qy_num;
    @BindView(R.id.tv_cp_num)
    TextView tv_cp_num;
    @BindView(R.id.view_myline)
    View view_myline;
    @BindView(R.id.tv_dingyue)
    TextView tv_dingyue;
    @BindView(R.id.details_phone_iv)
    ImageView details_phone_iv;
    @BindView(R.id.details_collection_iv)
    ImageView details_collection_iv;
    @BindView(R.id.ll_mores)
    LinearLayout ll_mores;
    @BindView(R.id.tv_qixian)
    TextView tv_qixian;


//    PagerSlidingTabStrip id_stickynavlayout_indicator;

    ProductDetailItemAdapter mAdapter;

    //Fragment的数据集合
    List<Fragment> fragmentList = null;
    //标题数据集合
    List<String> titles = null;

    private PKBean pkBean;

    private ProductInfoBean bean;
    private String phone;
    private String id, userId;
    private String isFast = "0";
    private String name;
    private GoodBadDialogFragment dialogFragment;
    private PopupWindow popupWindow;
    private String recruitmentStatus;

//    @BindView(R.id.id_stickynavlayout_indicator)
//    PagerSlidingTabStrip pagerSlidingTabStrip;

    //剪切板管理工具类
    private ClipboardManager mClipboardManager;
    //剪切板Data对象
    private ClipData mClipData;
    private boolean flag = true;

    private boolean canClick = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_product_details_new1;
    }

    @Override
    protected void onResume() {
        super.onResume();

        if(AppUtil.isExamined1(ProductDetailsActivity.this)){
            productInfo(id, isFast);
        }else{
            MobclickAgent.onEvent(ProductDetailsActivity.this, "home_click_product");
        }

    }

    @Override
    public void showMsg(String msg) {
        super.showMsg(msg);
        if("此产品已下架，请浏览其它产品".equals(msg))
            ProductDetailsActivity.this.finish();

//        fragmentList = new ArrayList<>();
//        BaseInfoFragment baseInfoFragment = new BaseInfoFragment();
////        Bundle bundle = new Bundle();
////        bundle.putSerializable("baseInfo",bean);
////        baseInfoFragment.setArguments(bundle);
//        AccountFragment accountFragment = new AccountFragment();
////        accountFragment.setArguments(bundle);
//        ProductListFragment productListFragment = new ProductListFragment();
////        productListFragment.setArguments(bundle);
//
//        ProductPictFragment productPictFragment = new ProductPictFragment();
////        productPictFragment.setArguments(bundle);
//
////            JigouFragment2 jigouFragment = new JigouFragment2();
////            jigouFragment.setArguments(bundle);
////            fragmentList.add(jigouFragment);
//        fragmentList.add(baseInfoFragment);
//        fragmentList.add(accountFragment);
//        fragmentList.add(productListFragment);
//        fragmentList.add(productPictFragment);
//
//        titles = new ArrayList<>();
////            titles.add("机构相关");
//        titles.add("基本资料");
//        titles.add("募集账号");
//        titles.add("相关产品");
//        titles.add("相关材料");
//
//        new TabLayoutUtil(getSupportFragmentManager(), findViewById(R.id.rl_product_details_new), fragmentList, titles, 102);
    }

    @Override
    protected void initView() {
        if (getIntent() != null) {
            id = getIntent().getStringExtra("id");
            isFast = getIntent().getStringExtra("isFast");
        }
        mClipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        userId = AppUtil.getUserId(this);
        mAdapter = new ProductDetailItemAdapter(this);
        rv_product_detail.setLayoutManager(new LinearLayoutManager(this));
        rv_product_detail.setHasFixedSize(true);
        rv_product_detail.setAdapter(mAdapter);


    }


    public void editNum(){
        details_compare_num_tv.setVisibility(View.VISIBLE);
        int currentNum=Integer.valueOf(bean.getNum())+1;
        bean.setNum(currentNum+"");
        details_compare_num_tv.setText(currentNum+"");
    }

    public void dingyue(){
        ToastUtils.showToast(ProductDetailsActivity.this,"确定订阅");
    }



    @OnClick({R.id.ll_goto_detail,R.id.ll_sh,R.id.details_title_back_rl,R.id.etails_plus_rl,R.id.details_duibi_tv,R.id.pk,R.id.details_phone_rl, R.id.details_collection_rl,R.id.details_share_rl,R.id.details_pro_tv,R.id.img_copy})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.ll_goto_detail:
                if(!TextUtils.isEmpty(id)){

                    HttpManager.getInstance().userOrderTypeInfo(AppUtil.getUserId(this)).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean1>() {
                        @Override
                        public void onNext(ResultBean1 o) {

                            if(!o.getStatus().equals("0")){
                                ShouchongFragment dialogFragment = new ShouchongFragment();
                                Bundle args = new Bundle();
                                args.putString("imgUrl",o.getUrlImg());
                                dialogFragment.setArguments(args);
                                dialogFragment.setCancelable(false);
                                dialogFragment.show(getFragmentManager(),"");
//                                ZhuanyeFragment dialogFragment = new ZhuanyeFragment();

//                    dialogFragment.setActivity(ProductDetailsActivity.this);
//                                dialogFragment.setCancelable(false);
//                                dialogFragment.show(getFragmentManager(),"");
//                                startActivity(new Intent().setClass(ProductDetailsActivity.this,ZhoubianActivity.class).putExtra("proId",id));
                            }else{
                                startActivity(new Intent().setClass(ProductDetailsActivity.this,ZhoubianActivity.class).putExtra("proId",id));
                            }

                        }
                    }, this));
                }

                break;
            case R.id.ll_sh:
                ptlm.scrollToTop();
                ptlm.scrollToBottom();
                break;
            case R.id.details_title_back_rl:
                finish();
                break;
            // 对比
            case R.id.details_duibi_tv:
                if (AppUtil.isExamined(this)) {
                    if(canClick)
                        startActivity(new Intent(this, ProductCompareActivity.class));
                }
                break;
            // 加对比
            case R.id.etails_plus_rl:
                if (AppUtil.isExamined(this)) {
                    addCompare(id, userId);
                }
                break;
            case R.id.pk:
                if (AppUtil.isExamined(this)) {
                    if(canClick)
                        pkInfo(AppUtil.getUserId(this), id);
                }
//                else {
//                    pkInfo("", id);
//                }
                break;
            // 订阅
            case R.id.details_phone_rl:
//                ToastUtils.showToast(ProductDetailsActivity.this,"订阅");
                // 订阅接口
                if(canClick){
                    if(!bean.getScribe().equals("0")){
//                    DingyueProductFragment dingyueFragment = new DingyueProductFragment();
//
//                    dingyueFragment.setCancelable(false);
//                    dingyueFragment.show(getFragmentManager(),"");

                        if(pd!=null)
                            pd.show();
                        HttpManager.getInstance().usersubscribe(AppUtil.getUserId(ProductDetailsActivity.this), id).compose(bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean1>() {
                            @Override
                            public void onNext(ResultBean1 o) {
                                if(o.getResult().equals("1")){
                                    tv_dingyue.setText("已订阅");
                                    bean.setScribeId(o.getScribeId());
                                    bean.setScribe("0");
                                    details_phone_iv.setImageResource(R.mipmap.home_dingyue_red);
                                    ToastUtils.showToast(ProductDetailsActivity.this, "订阅成功");
                                    bean.setScribe("0");
                                    if(pd!=null)
                                        pd.dismiss();
                                }
                            }
                        }, this));


                        // 未订阅状态
                    }else{
                        if(canClick){
                            if(pd!=null)
                                pd.show();
                            HttpManager.getInstance().userSubscribeDelete(bean.getScribeId()).compose(bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean1>() {
                                @Override
                                public void onNext(ResultBean1 o) {
                                    if(o.getResult().equals("1")){
                                        tv_dingyue.setText("订阅");
                                        bean.setScribeId("");
                                        bean.setScribe("1");
                                        details_phone_iv.setImageResource(R.mipmap.home_dingyue_black);
                                        ToastUtils.showToast(ProductDetailsActivity.this, "取消订阅成功");
                                        if(pd!=null)
                                            pd.dismiss();
//                                bean.setScribe("0");
                                    }
                                }
                            }, this));
                        }


                    }
                }


//                if (!phone.equals("")) {
//                    try{
//                        Intent intent = new Intent(Intent.ACTION_DIAL);
//                        Uri data = Uri.parse("tel:" + phone);
//                        intent.setData(data);
//                        startActivity(intent);
//                    }catch(Exception e){
//                        ToastUtils.showToast(ProductDetailsActivity.this,"您的手机暂时不支持此功能");
//                    }
//
//                }else{
//                    ToastUtils.showToast(ProductDetailsActivity.this,"该产品暂时不支持此功能");
//                }

//                startActivity(new Intent(ProductDetailsActivity.this,HyqxActivity1.class).putExtra("fxjg",bean.getBasic().get(0).getOrganization()));
                break;
            // 收藏
            case R.id.details_collection_rl:
                if (AppUtil.isExamined(this)) {
                    if(canClick){
                        String userid = AppUtil.getUserId(this);
                        collect(userid, id);
                    }

                }
                break;
            // 分享
            case R.id.details_share_rl:
                if (AppUtil.isExamined(this)){
                    if(canClick)
                        showBottomPopuWindow();
                }

                break;
            // 预约产品
            case R.id.details_pro_tv:
//                if (AppUtil.isExamined(this)) {
//
//                    if (recruitmentStatus.equals("募集中")) {//预约
//                        startActivity(new Intent(this, AppointProductActivity.class).putExtra("id", id).putExtra("name", name).putExtra("startAmount", bean.getStartAmount()).putExtra("isFast", isFast));
//                    } else if (recruitmentStatus.equals("预热中")) {//认购
//                        startActivity(new Intent(this, SubscriptionProductActivity.class).putExtra("id", id).putExtra("name", name).putExtra("startAmount", bean.getStartAmount()).putExtra("isFast", isFast));
//                    }
//                }
//                MPopWindow popWindow = new MPopWindow(ProductDetailsActivity.this,phone);
//                popWindow.showPopupWindow(rl_product_details_new);
//                showPop();
                if(canClick)
                    getZixun();
//                BasicDialog1.Builder builder = new BasicDialog1.Builder(ProductDetailsActivity.this);
//                builder.setMessage("呼叫:"+phone)
//                        .setPositiveButton("呼叫", new AlertDialog.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                if (!phone.equals("")) {
//                                    try{
//                                        Intent intent = new Intent(Intent.ACTION_DIAL);
//                                        Uri data = Uri.parse("tel:" + phone);
//                                        intent.setData(data);
//                                        startActivity(intent);
//                                    }catch(Exception e){
//                                        ToastUtils.showToast(ProductDetailsActivity.this,"您的手机暂时不支持此功能");
//                                    }
//
//                                }else{
//                                    ToastUtils.showToast(ProductDetailsActivity.this,"该产品暂时不支持此功能");
//                                }
//                                dialog.dismiss();
//                            }
//
//                        })
//                        .setNegativeButton("取消", new AlertDialog.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                            }
//                        });
//
//                builder.create().show();

                break;

            case R.id.img_copy:
                if(canClick){
                    //创建一个新的文本clip对象
                    try{
                        String funduse = TextUtils.isEmpty(bean.getFundUse())?"暂无数据":bean.getFundUse();
                        mClipData = ClipData.newPlainText("Simple test", "产品名称:"+ bean.getBasic().get(0).getName()+"\n"
                                +"募集进度:"+bean.getInfo().get(0).getShelfState() + "%\n"
                                +"期限:"+bean.getInvestmentTerm()+"\n"
                                +"规模:"+bean.getScale()+"\n"
                                +"收益:"+bean.getExpectReturn()+"\n"
                                +"付息方式:"+(TextUtils.isEmpty(bean.getBasic().get(0).getMethod())?"暂无数据":bean.getBasic().get(0).getMethod())+"\n"
                                +"资金用途:"+ funduse);
//                            +"\n"+"亮点:"+bean.getInfo().get(0).getLabels()

                        //把clip对象放在剪贴板中
                        mClipboardManager.setPrimaryClip(mClipData);
                        ToastUtils.showToast(ProductDetailsActivity.this,"一键复制成功");
                    }catch(Exception e){
                        ToastUtils.showToast(ProductDetailsActivity.this,"复制失败");
                    }
                }

                break;

        }

    }

    /**
     * 底部弹出层
     */
    private void showBottomPopuWindow() {
        LinearLayout rootView = (LinearLayout) LayoutInflater.from(this).inflate(
                R.layout.dialog_share_board, null);

        popupWindow = new PopupWindow(rootView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        TextView cancelT = (TextView) rootView.findViewById(R.id.btn_cancel);
        cancelT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        LinearLayout wechatL = (LinearLayout) rootView.findViewById(R.id.share_wechat);
        wechatL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                shareProduct(AppUtil.getUserId(ProductDetailsActivity.this), id, SHARE_MEDIA.WEIXIN);
                popupWindow.dismiss();
            }
        });
        LinearLayout wxCircleL = (LinearLayout) rootView.findViewById(R.id.share_wxcircle);
        wxCircleL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                shareProduct(AppUtil.getUserId(ProductDetailsActivity.this), id, SHARE_MEDIA.WEIXIN_CIRCLE);
                popupWindow.dismiss();
            }
        });
        LinearLayout sinaL = (LinearLayout) rootView.findViewById(R.id.share_sina);
        sinaL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                shareProduct(AppUtil.getUserId(ProductDetailsActivity.this), id, SHARE_MEDIA.QQ);
                popupWindow.dismiss();
            }
        });
        LinearLayout emailL = (LinearLayout) rootView.findViewById(R.id.share_email);
        emailL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                shareProduct(AppUtil.getUserId(ProductDetailsActivity.this), id, SHARE_MEDIA.QZONE);
                popupWindow.dismiss();
            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
    }

    private void shareProduct(String userId, String proId, final SHARE_MEDIA type) {
        HttpManager.getInstance().shareProduct(userId, proId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ShareProductBean>() {
            @Override
            public void onNext(ShareProductBean o) {

                share(o.getName(), o.getContent(), o.getUrl(), o.getImg(), type);
            }
        }, this));
    }

    private void collect(String userid, String id) {
        HttpManager.getInstance().collect(userid, id).compose(bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<CollectBean>() {
            @Override
            public void onNext(CollectBean o) {
                if (o.getState().equals("0")) {
                    details_collection_tv.setText("已收藏");
                    details_collection_iv.setImageResource(R.mipmap.collect_collect_red);
                    ToastUtils.showToast(ProductDetailsActivity.this, "收藏成功");
                } else {
                    details_collection_tv.setText("收藏");
                    details_collection_iv.setImageResource(R.mipmap.collect_collect_black);
                    ToastUtils.showToast(ProductDetailsActivity.this, "已取消收藏");
                }
            }
        }, this));
    }

    private void addCompare(final String proId, String userId) {

        HttpManager.getInstance().addCompare(proId, userId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
                if (o.getResult().equals("1")) {
                    ToastUtils.showToast(ProductDetailsActivity.this, "添加成功");
//                    productInfo(proId, isFast);
                    details_plus_tv.setText("已添加");
                    etails_plus_rl.setBackgroundResource(R.drawable.corens_100_style_a10_new);
                    int myNum = Integer.valueOf(bean.getNum())+1;
                    bean.setNum(myNum+"");
                    details_compare_num_tv.setText(myNum+"");
                    details_compare_num_tv.setVisibility(View.VISIBLE);
                }
            }
        }, this));
    }

    private void pkInfo(String userId, String proId) {
        HttpManager.getInstance().pkInfo(userId, proId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<PKBean>() {
            @Override
            public void onNext(PKBean o) {
                dialogFragment = new GoodBadDialogFragment();
                Bundle bundle = new Bundle();
                bundle.putSerializable("pk1", pkBean);
                bundle.putSerializable("pk2", o);
                bundle.putString("nowId", id);
                dialogFragment.setArguments(bundle);
                dialogFragment.show(getFragmentManager(), "");
            }
        }, this));
    }

    /**
     * 分享到平台
     *
     * @param plarform
     */
    private void share(String title, String content, String url, String img, SHARE_MEDIA plarform) {
        UMImage thumb = new UMImage(ProductDetailsActivity.this, img);
        UMWeb web = new UMWeb(url);
        web.setThumb(thumb);
        web.setDescription(content);
        web.setTitle(title);
        new ShareAction(ProductDetailsActivity.this)
                .withMedia(web)
                .setPlatform(plarform)
                .setCallback(umShareListener)
                .share();
    }

    /**
     * 产品详情
     *
     * @param id
     */
    private void productInfo(String id, String isFast) {
        HttpManager.getInstance().productInfo(AppUtil.getUserId(this), id, "0", "10", isFast).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ProductInfoBean>() {
            @Override
            public void onNext(ProductInfoBean o) {
                bean = o;
                if(o.getResult().equals("2")){
                    if(o.getSum()==0){
                        setViewData(o);
                    }else if(o.getSum()==1){
                        ShouchongFragment dialogFragment = new ShouchongFragment();
                        Bundle args = new Bundle();
                        args.putString("imgUrl",o.getUrlImg());
                        dialogFragment.setArguments(args);
                        dialogFragment.setCancelable(false);
                        dialogFragment.show(getFragmentManager(),"");
                    }else{
                        FreeFragment freeFragment = new FreeFragment();
                        freeFragment.setCancelable(false);
                        freeFragment.show(getFragmentManager(),"");
//                        showFreePop("","");
                        setViewData(o);
                    }
//                    FreeFragment dialogFragment = new FreeFragment();
//                    LogUtils.e("sfZ","description:"+o.getDescription()+",value:"+o.getValue());
//                    Bundle args = new Bundle();
//                    args.putString("description", o.getDescription());
//                    args.putString("value", o.getValue());
//                    dialogFragment.setArguments(args);

//                    dialogFragment.setActivity(ProductDetailsActivity.this);
//                    dialogFragment.setCancelable(false);
//                    dialogFragment.show(getFragmentManager(),"");
                }else{
                    canClick = true;
                    setViewData(o);
                }

            }
        }, this));
    }



    private void setViewData(ProductInfoBean bean) {

        try{
            if(Integer.valueOf(bean.getCompanyCount())==0){
                ll_goto_detail.setVisibility(View.GONE);
//            view_myline
                }else{
                    ll_goto_detail.setVisibility(View.VISIBLE);
                tv_qy_num.setText(bean.getCompanyCount()+"");
                tv_cp_num.setText  (bean.getProCount()+"");
            }
        }catch (Exception e){
            ll_goto_detail.setVisibility(View.GONE);
        }

//pk
        pkBean = new PKBean(bean.getIsCollateralize(), bean.getBasic().get(0).getName(), bean.getInvestmentTerm(), bean.getExpectReturn(), bean.getCommission(),"",bean.getInfo().get(0).getProType());
        //对比
        if (bean.getNum().equals("0")) {
            details_compare_num_tv.setVisibility(View.GONE);
        } else {
            details_compare_num_tv.setVisibility(View.VISIBLE);
            details_compare_num_tv.setText(bean.getNum());
        }
        //基本资料
        ProductInfoBean.BasicBean basicBean = bean.getBasic().get(0);
        name = basicBean.getName();
        phone = bean.getPhone();

        details_pro_name_tv.setText(basicBean.getName());

        tv_detail_qt.setText(bean.getStartAmount());
        tv_detail_sy.setText(bean.getExpectReturn().replace("%",""));
        String qxStr = bean.getInvestmentTerm().replace("个月","");
        if(qxStr.contains("+")){

            tv_detail_qx.setText(qxStr.substring(0,qxStr.indexOf("+")+1));
            ll_mores.setVisibility(View.VISIBLE);
            tv_qixian.setText(qxStr);
        }else{
            tv_detail_qx.setText(qxStr);
        }


        //产品信息
        ProductInfoBean.InfoBean infoBean = bean.getInfo().get(0);
        tv_detail.setText(infoBean.getProType());

        recruitmentStatus = infoBean.getRecruitmentStatus();

        // 预热和图片
        if(infoBean.getImgstuats().equals("1")){
            img_tu.setVisibility(View.VISIBLE);
        }else{
            img_tu.setVisibility(View.GONE);
        }

        if(recruitmentStatus.equals("预热中"))
            img_yu.setVisibility(View.VISIBLE);
        else{
            img_yu.setVisibility(View.GONE);
        }

        // 实时信息
//        tv_detail_now_info.setText("[实时信息]"+infoBean.getCurrentInfo());
        if(!TextUtils.isEmpty(infoBean.getCurrentInfo())){

        }else{
            infoBean.setCurrentInfo("暂无信息");
        }
        tv_detail_now_info.setText(Html.fromHtml("<b>[实时信息]</b>"+infoBean.getCurrentInfo()));
        //收益率
        List<ProductInfoBean.RateBean> rateBeen = bean.getRate();

        mAdapter.addData(rateBeen);
        // 亮点标签
        List<String> list = Arrays.asList(infoBean.getLabels().split(","));
        details_lable_flowlayout.cleanTag();
        details_lable_flowlayout.setDatasProduct(list);
        // 状态
        details_state_type_tv.setText(infoBean.getRecruitmentStatus());


        if(MySelfInfo.getInstance().getIsPay().equals("0")){
            details_state_pro_tv.setText(infoBean.getShelfState() + "%");
            // 进度条
            if (!infoBean.getShelfState().equals("")) {
                String[] splitPres = new String[2];
                splitPres = infoBean.getShelfState().split("\\.");
                if (splitPres.length > 1) {
                    details_state_pb.setProgress(Integer.parseInt(splitPres[0]));
                } else {
                    details_state_pb.setProgress(Integer.parseInt(infoBean.getShelfState()));
                }
            }
        }else{
            details_state_pro_tv.setText("会员可见");
            details_state_pb.setProgress(0);
        }

        // 付息方式
        details_fxfs_tv.setText(basicBean.getMethod());
        if(bean.getIsCompared().equals("1")){
            details_plus_tv.setText("已添加");
            etails_plus_rl.setBackgroundResource(R.drawable.corens_100_style_a10_new);
        }else{
            details_plus_tv.setText("加对比");
            etails_plus_rl.setBackgroundResource(R.drawable.background_login_btn);

        }

        if (bean.getIsCollect().equals("1")) {
            details_collection_tv.setText("已收藏");
            details_collection_iv.setImageResource(R.mipmap.collect_collect_red);
        } else {
            details_collection_tv.setText("收藏");
            details_collection_iv.setImageResource(R.mipmap.collect_collect_black);
        }

        // 已订阅
        if(bean.getScribe().equals("0")){
            tv_dingyue.setText("已订阅");
            details_phone_iv.setImageResource(R.mipmap.home_dingyue_red);
        }else{
            tv_dingyue.setText("订阅");
            details_phone_iv.setImageResource(R.mipmap.home_dingyue_black);
        }


//        if (infoBean.getRecruitmentStatus().equals("预热中")) {
////            details_pro_tv.setText("认购");
//        } else if (infoBean.getRecruitmentStatus().equals("募集中")) {
////            details_pro_tv.setText("预约产品");
//        } else {
//            details_pro_tv.setText("售罄");
//            details_pro_tv.setClickable(false);
//            details_pro_tv.setTextColor(Color.parseColor("#ffffff"));
//            details_pro_tv.setBackgroundColor(getResources().getColor(R.color.gray));
//            details_state_type_tv.setText("售罄");
//        }
        if(flag){
            flag =false;
            fragmentList = new ArrayList<>();
            BaseInfoFragment baseInfoFragment = new BaseInfoFragment();
            Bundle bundle = new Bundle();
            bundle.putSerializable("baseInfo",bean);
            baseInfoFragment.setArguments(bundle);
            AccountFragment accountFragment = new AccountFragment();
            accountFragment.setArguments(bundle);
            ProductListFragment productListFragment = new ProductListFragment();
            productListFragment.setArguments(bundle);

            ProductPictFragment productPictFragment = new ProductPictFragment();
            productPictFragment.setArguments(bundle);

//            JigouFragment2 jigouFragment = new JigouFragment2();
//            jigouFragment.setArguments(bundle);
//            fragmentList.add(jigouFragment);
            fragmentList.add(baseInfoFragment);
            fragmentList.add(accountFragment);
            fragmentList.add(productListFragment);
            fragmentList.add(productPictFragment);

            titles = new ArrayList<>();
//            titles.add("机构相关");
            titles.add("基本资料");
            titles.add("募集账号");
            titles.add("相关产品");
            titles.add("相关材料");

            new TabLayoutUtil(getSupportFragmentManager(), findViewById(R.id.rl_product_details_new), fragmentList, titles, 102);
        }else{
            if(updateListener!=null)
                updateListener.updateList(bean);
        }

    }
    UpdateListener updateListener;

    public interface UpdateListener{
        public void updateList(ProductInfoBean bean);
    }
    public void setListener(UpdateListener listener){
        this.updateListener = listener;
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            //分享开始的回调
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.d("plat", "platform" + platform);
//            ToastUtils.showToast(ProductDetailsActivity.this, " 分享成功啦");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtils.showToast(ProductDetailsActivity.this, " 分享失败啦");
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtils.showToast(ProductDetailsActivity.this, " 分享取消了");
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }


    private List<ZixunBean.MemberBean> zixunBeanList = new ArrayList<>();
    private ZixunAdapter zixunAdapter;
    private PopupWindow popupWindow_zixun;
    private boolean haveZixun = false;

    // 咨询按钮
    private void getZixun(){

        HttpManager.getInstance().rebatePay(userId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
                if(o.getStatus().equals("1")){
                    ShouchongFragment dialogFragment = new ShouchongFragment();
                    Bundle args = new Bundle();
                    args.putString("imgUrl",o.getUrlImg());
                    dialogFragment.setArguments(args);
                    dialogFragment.setCancelable(false);
                    dialogFragment.show(getFragmentManager(),"");


//                    showFreePop(o.getDescription(),o.getValue());

                }else{
                    getPay();
                }

            }
        }, this));
//        getPay();
//        showFreePop();
    }


    private void getPay(){
        if(haveZixun){
            if(zixunBeanList!=null&&zixunBeanList.size()>0){
                showPop();
            }else{
                if(TextUtils.isEmpty(phone)){
                    callPhone(str2);
                }else
                    callPhone(phone);
            }
        }else {
            HttpManager.getInstance().rebate(AppUtil.getUserId(ProductDetailsActivity.this), id).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ZixunBean>() {
                @Override
                public void onNext(ZixunBean o) {
                    zixunBeanList = o.getProList();
                    ProductDetailsActivity.this.pd.dismiss();
                    haveZixun = true;
                    if (zixunBeanList != null && zixunBeanList.size() > 0) {
                        showPop();
                    } else {
                        if(TextUtils.isEmpty(phone)){
                            callPhone(str2);
                        }else
                            callPhone(phone);
                    }

                }
            }, this));
        }
    }
    private String str2 = "4000805050";
    public void showPop() {

        if(popupWindow_zixun==null){
            LinearLayout rootView = (LinearLayout) LayoutInflater.from(this).inflate(
                    R.layout.pop_zixun, null);

            popupWindow_zixun = new PopupWindow(rootView, ViewGroup.LayoutParams.MATCH_PARENT,((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight()*2/3);
            RecyclerView zixun_rv = (RecyclerView) rootView.findViewById(R.id.zixun_rv);
            zixunAdapter = new ZixunAdapter(ProductDetailsActivity.this);
            zixun_rv.setLayoutManager(new LinearLayoutManager(this));
            zixun_rv.setHasFixedSize(true);
            zixun_rv.setAdapter(zixunAdapter);
            zixunAdapter.addData(zixunBeanList);
            TextView tv_tip = (TextView) rootView.findViewById(R.id.tv_tip);
            String str1 = "下列咨询信息，已由本平台严格审核。若有任何疑问请咨询搜搜出单官方客服热线";

            String str3 = "。";
            String allstr = str1+str2+str3;
            SpannableString style = new SpannableString(allstr);
            style.setSpan(new ForegroundColorSpan(Color.parseColor("#4a4a4a")), 1,
                    str1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            style.setSpan(new ForegroundColorSpan(Color.parseColor("#3D89E1")), str1.length(),
                    allstr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            style.setSpan(new Clickable(clickListener),str1.length(),allstr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv_tip.setText(style);
            tv_tip.setMovementMethod(LinkMovementMethod.getInstance());
            popupWindow_zixun.setFocusable(true);
            popupWindow_zixun.setBackgroundDrawable(new BitmapDrawable());
            popupWindow_zixun.setOutsideTouchable(true);
            popupWindow_zixun.setTouchable(true);
            popupWindow_zixun.setAnimationStyle(R.style.mypopwindow_anim_style);
            popupWindow_zixun.showAtLocation(rl_product_details_new, Gravity.BOTTOM, 0, 0);


        }else{
            popupWindow_zixun.showAtLocation(rl_product_details_new, Gravity.BOTTOM, 0, 0);
        }
    }
    private PopupWindow popupWindow_free;
    public void showFreePop(final String  description,final String value) {

        if(popupWindow_free==null){
            RelativeLayout rootView = (RelativeLayout) LayoutInflater.from(this).inflate(
                    R.layout.pop_free1, null);
//            ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight()*2/3
            popupWindow_free = new PopupWindow(rootView, ViewGroup.LayoutParams.MATCH_PARENT,((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight()*2/3);

            popupWindow_free.setFocusable(false);
            popupWindow_free.setBackgroundDrawable(new BitmapDrawable());
            popupWindow_free.setOutsideTouchable(false);
            popupWindow_free.setTouchable(false);
//            popupWindow_free.setAnimationStyle(R.style.mypopwindow_anim_style);
            popupWindow_free.showAtLocation(rl_product_details_new, Gravity.BOTTOM, 0, 0);
            TextView refresh_tv = (TextView) rootView.findViewById(R.id.refresh_tv);
            TextView tv1 = (TextView) rootView.findViewById(R.id.textview1);
            TextView tv2 = (TextView) rootView.findViewById(R.id.textview2);
//            tv1.setText(description);
//            tv2.setText(value);
            refresh_tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    popupWindow_free.dismiss();
                    startActivity(new Intent(ProductDetailsActivity.this,PayActivity.class));
                    ProductDetailsActivity.this.finish();
                }
            });
            TextView tv_return = (TextView) rootView.findViewById(R.id.tv_return);
            tv_return.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    popupWindow_free.dismiss();
                    ProductDetailsActivity.this.finish();

                }
            });

//            if(flag){
//                popupWindow_free.setOnDismissListener(new PopupWindow.OnDismissListener() {
//                    @Override
//                    public void onDismiss() {
//                        if(popupWindow_zixun!=null&&popupWindow_zixun.isShowing())
//                            popupWindow_zixun.dismiss();
//                        popupWindow_free.dismiss();
//                    }
//                });
//            }else{
//                popupWindow_free.setOnDismissListener(new PopupWindow.OnDismissListener() {
//                    @Override
//                    public void onDismiss() {
//                        if(popupWindow_zixun!=null&&popupWindow_zixun.isShowing())
//                            popupWindow_zixun.dismiss();
//                    }
//                });
//            }


        }else{
            popupWindow_free.showAtLocation(rl_product_details_new, Gravity.BOTTOM, 0, 0);
        }
    }



    private View.OnClickListener clickListener=new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            callPhone(str2);
        }
    };

    /**
     * 打电话
     * @param phone_num
     */
    public void callPhone(final String phone_num){

        BasicDialog1.Builder builder = new BasicDialog1.Builder(ProductDetailsActivity.this);
        builder.setMessage("呼叫:"+phone_num)
                .setPositiveButton("呼叫", new AlertDialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (!phone_num.equals("")) {
                            try{
                                Intent intent = new Intent(Intent.ACTION_DIAL);
                                Uri data = Uri.parse("tel:" + phone_num);
                                intent.setData(data);
                                startActivity(intent);
                            }catch(Exception e){
                                ToastUtils.showToast(ProductDetailsActivity.this,"您的手机暂时不支持此功能");
                            }

                        }else{
                            ToastUtils.showToast(ProductDetailsActivity.this,"本产品联系电话即将开放");
                        }
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new AlertDialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();
    }



    public void phoneCall(final String cid,final String phone_num){
        HttpManager.getInstance().rebatePay(userId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
                if(o.getStatus().equals("1")){
//                    showFreePop(o.getDescription(),o.getValue());
                    ShouchongFragment dialogFragment = new ShouchongFragment();
                    Bundle args = new Bundle();
                    args.putString("imgUrl",o.getUrlImg());
                    dialogFragment.setArguments(args);
                    dialogFragment.setCancelable(false);
                    dialogFragment.show(getFragmentManager(),"");

                }else{
                    phoneCall1(cid,phone_num);
                }

            }
        }, this));

    }

    public void phoneCall1(String cid,final String phone_num){
        HttpManager.getInstance().rebateLogs(userId,id,cid).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
//
                callPhone(phone_num);

            }
        }, this));
    }

    class Clickable extends ClickableSpan {
        private final View.OnClickListener mListener;

        public Clickable(View.OnClickListener l) {
            mListener = l;
        }

        /**
         * 重写父类点击事件
         */
        @Override
        public void onClick(View v) {
            mListener.onClick(v);
        }

        /**
         * 重写父类updateDrawState方法  我们可以给TextView设置字体颜色,背景颜色等等...
         */
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(getResources().getColor(R.color.color2));
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(popupWindow_free!=null&&popupWindow_free.isShowing()){
                popupWindow_free.dismiss();
            }
            if(popupWindow!=null&&popupWindow.isShowing()){
                popupWindow.dismiss();
            }
            if(popupWindow_zixun!=null&&popupWindow_zixun.isShowing()){
                popupWindow_zixun.dismiss();
            }
            ProductDetailsActivity.this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }

//    @Override
//    public boolean dispatchTouchEvent(MotionEvent event){
//        if(popupWindow_free!=null&&popupWindow_free.isShowing()){
//            return false;
//        }
////        if(popupWindow!=null&&popupWindow.isShowing()){
////            return false;
////        }
////        if(popupWindow_zixun!=null&&popupWindow_zixun.isShowing()){
////            return false;
////        }
//        return super.dispatchTouchEvent(event);
//    }


}
